package com.shenjinzheng.movie_ticket_app.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.shenjinzheng.movie_ticket_app.activity.MovieDetailActivity
import com.shenjinzheng.movie_ticket_app.databinding.ItemMovieBinding
import com.shenjinzheng.movie_ticket_app.model.Movie

class MovieAdapter(private var movies: List<Movie>, private val context: Context) : RecyclerView.Adapter<MovieAdapter.MovieViewHolder>() {

    // 更新适配器数据
    fun updateMovies(newMovies: List<Movie>) {
        this.movies = newMovies
        notifyDataSetChanged()  // 通知适配器更新数据
    }

    // 创建 ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
        val binding = ItemMovieBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MovieViewHolder(binding)
    }

    // 绑定数据
    override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
        val movie = movies[position]
        holder.bind(movie)
    }

    // 返回数据集大小
    override fun getItemCount(): Int = movies.size

    // ViewHolder 用来绑定数据
    inner class MovieViewHolder(private val binding: ItemMovieBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(movie: Movie) {
            binding.movie = movie  // 绑定电影数据到视图
            binding.executePendingBindings()  // 执行绑定

            // 点击事件，跳转到电影详情页
            itemView.setOnClickListener {
                val intent = Intent(context, MovieDetailActivity::class.java)
                intent.putExtra("movie", movie)  // 传递电影数据
                context.startActivity(intent)
            }
        }
    }
}